package com.zeek.car90s;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.mediation.admob.AdMobAdapter;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.NativeExpressAdView;
import com.google.android.gms.ads.reward.RewardItem;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;
import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.game.UMGameAgent;
import com.zeek.car90s.util.MediaPlayerUtils;
import com.zeek.car90s.util.SoundPoolUtils;
import com.zeek.car90s.util.Tools;

import java.util.Calendar;

public class EarnCoinsActivity extends AppCompatActivity implements View.OnClickListener, RewardedVideoAdListener {

    private Button btnBack, btnCoin, btnBonus, coinBonus, btnRateAp, coinRateApp,
            btnFeelingLucky, coinFeelingLucky, btnWatchVideo, coinWatchVideo, btnMoreGames, coinsMoreGames;
    private SharedPreferences sp;
    private Chronometer chronometer;
    private TextView tvBonus, tvFeelingLucky, tvMoreGames;
    private int countSign, storageDay;

    private boolean mIsRewardedVideoLoading;
    private final Object mLock = new Object();//视屏广告锁

    private static final int MAX_SIGN_COUNT = 1;
    //    private RewardedVideoAd rewardedVideoAd;
    private LinearLayout llWatchVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_earn_coins);

        sp = getSharedPreferences(Constants.SHARED_PREFERENCE_PREFIX, Context.MODE_PRIVATE);

        //让每天执行一次的初始逻辑
        countSign = sp.getInt("count_sign", 0);
        storageDay = sp.getInt("day", -1);

        Calendar cal = Calendar.getInstance();
        int myDay = cal.get(Calendar.DATE);
        if (myDay != storageDay) {
            countSign = 0;
            SharedPreferences.Editor editor = sp.edit();
            editor.putInt("day", myDay);
            editor.apply();
        }

        //初始化视频激励
//        Constants.rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
        Constants.rewardedVideoAd.setRewardedVideoAdListener(this);
        if (!Constants.rewardedVideoAd.isLoaded()) {
            loadRewardedVideoAd();
        }

        //展示原生广告
        NativeExpressAdView adView = (NativeExpressAdView) findViewById(R.id.adView);
        adView.loadAd(new AdRequest.Builder().build());

        initView();
    }

    private void initView() {
        //返回和金币按钮
        btnBack = (Button) findViewById(R.id.button_back);
        btnBack.setOnClickListener(this);

        btnCoin = (Button) findViewById(R.id.btn_game_coin);
        btnCoin.setOnClickListener(this);
        btnCoin.setText(Constants.TOTAL_COIN + "");

        chronometer = (Chronometer) findViewById(R.id.chronometer);

        //Bonus奖励
        btnBonus = (Button) findViewById(R.id.btn_bonus);
        btnBonus.setOnClickListener(this);

        coinBonus = (Button) findViewById(R.id.coin_bonus);
        coinBonus.setText("+" + Constants.COINS_EARN_BONUS);
        coinBonus.setOnClickListener(this);

        tvBonus = (TextView) findViewById(R.id.tv_bonus);

        //Watch Video奖励
        btnWatchVideo = (Button) findViewById(R.id.btn_watch_video);
        btnWatchVideo.setOnClickListener(this);

        coinWatchVideo = (Button) findViewById(R.id.coin_watch_video);
        coinWatchVideo.setOnClickListener(this);
        coinWatchVideo.setText("+" + Constants.COINS_EARN_WATCH_VIDEO);
        llWatchVideo=(LinearLayout) findViewById(R.id.ll_watch_video);
        if(Constants.rewardedVideoAd.isLoaded()){
            llWatchVideo.setVisibility(View.VISIBLE);
        }else {
            llWatchVideo.setVisibility(View.INVISIBLE);
            loadRewardedVideoAd();
        }

        //I'm Feeling Lucky
        btnFeelingLucky = (Button) findViewById(R.id.btn_feeling_lucky);
        btnFeelingLucky.setOnClickListener(this);

        coinFeelingLucky = (Button) findViewById(R.id.coin_feeling_lucky);
        coinFeelingLucky.setOnClickListener(this);

        tvFeelingLucky = (TextView) findViewById(R.id.tv_feeling_lucky);

        //More Games
        btnMoreGames = (Button) findViewById(R.id.btn_more_games);
        btnMoreGames.setOnClickListener(this);

        coinsMoreGames = (Button) findViewById(R.id.coin_more_games);
        coinsMoreGames.setOnClickListener(this);
        coinsMoreGames.setText("+" + Constants.COINS_EARN_MORE_GAMES);

        tvMoreGames = (TextView) findViewById(R.id.tv_more_games);

        //评论app奖励
        btnRateAp = (Button) findViewById(R.id.btn_rate_app);
        btnRateAp.setOnClickListener(this);

        coinRateApp = (Button) findViewById(R.id.coin_rate_app);
        coinRateApp.setOnClickListener(this);
        coinRateApp.setText("+" + Constants.COINS_EARN_RATE_APP);

        //初始化Bonus倒计时钟
        Constants.START_TIME_BONUS = sp.getLong(Constants.START_TIME_BONUS_PREFIX, -1);
        if (Constants.START_TIME_BONUS != -1 && (System.currentTimeMillis() - Constants.START_TIME_BONUS) < Constants.BONUS_COINS_TIME) {
            startBonusClock();
            setBonusVisibility(false);
        } else {
            setBonusVisibility(true);

            Constants.START_TIME_BONUS = -1;
            SharedPreferences.Editor editor = sp.edit();
            editor.putLong(Constants.START_TIME_BONUS_PREFIX, -1);
            editor.commit();
        }

        //初始化FeelingLucky倒计时钟
        Constants.START_TIME_FEELING_LUCKY = sp.getLong(Constants.START_TIME_FEELING_LUCKY_PREFIX, -1);
        if (Constants.START_TIME_FEELING_LUCKY != -1 && (System.currentTimeMillis() - Constants.START_TIME_FEELING_LUCKY) < Constants.FEELING_LUCKY_COINS_TIME) {
            startFeelingLuckyClock();
            setFeelingLuckyVisibility(false);
        } else {
            setFeelingLuckyVisibility(true);

            Constants.START_TIME_FEELING_LUCKY = -1;
            SharedPreferences.Editor editor = sp.edit();
            editor.putLong(Constants.START_TIME_FEELING_LUCKY_PREFIX, -1);
            editor.commit();
        }

        //初始化More Games倒计时钟
        Constants.START_TIME_MORE_GAMES = sp.getLong(Constants.START_TIME_MORE_GAMES_PREFIX, -1);
        if (Constants.START_TIME_MORE_GAMES != -1 && (System.currentTimeMillis() - Constants.START_TIME_MORE_GAMES) < Constants.MORE_GAMES_COINS_TIME) {
            startFeelingLuckyClock();
            setFeelingLuckyVisibility(false);
        } else {
            setFeelingLuckyVisibility(true);

            Constants.START_TIME_MORE_GAMES = -1;
            SharedPreferences.Editor editor = sp.edit();
            editor.putLong(Constants.START_TIME_MORE_GAMES_PREFIX, -1);
            editor.commit();
        }
    }

    @Override
    public void onClick(View v) {
        MediaPlayerUtils.playNotification(1);
        int selectedId = v.getId();
        switch (selectedId) {
            case R.id.button_back:
                finish();
                break;
            case R.id.btn_bonus:
            case R.id.coin_bonus:
                getBonusCoins();
                break;
            case R.id.btn_watch_video:
            case R.id.coin_watch_video:
                getWatchVideoCoins();
                break;
            case R.id.btn_feeling_lucky:
            case R.id.coin_feeling_lucky:
                getFeelingLuckyCoins();
                break;
            case R.id.btn_more_games:
            case R.id.coin_more_games:
                getMoreGamesCoins();
                break;
            case R.id.btn_rate_app:
            case R.id.coin_rate_app:
                getRateAppCoins();
                break;
        }
    }

    //领取Bonus奖励
    private void getBonusCoins() {
        setBonusVisibility(false);

        Constants.START_TIME_BONUS = sp.getLong(Constants.START_TIME_BONUS_PREFIX, -1);
        if (Constants.START_TIME_BONUS == -1) {
            Constants.START_TIME_BONUS = System.currentTimeMillis();

            SharedPreferences.Editor editor = sp.edit();
            editor.putLong(Constants.START_TIME_BONUS_PREFIX, Constants.START_TIME_BONUS);
            editor.commit();
        }

        startBonusClock();

        handleCoin(Constants.COINS_EARN_BONUS);
        UMGameAgent.bonus("Bonus", 1, Constants.COINS_EARN_BONUS, 2);
        MobclickAgent.onEvent(EarnCoinsActivity.this, "get_coins_bonus");
    }

    //领取Watch Video的奖励
    private void getWatchVideoCoins() {
        if (Constants.rewardedVideoAd.isLoaded()) {
            Constants.rewardedVideoAd.show();
            UMGameAgent.bonus("Watch Video_earn", 1, Constants.COINS_EARN_WATCH_VIDEO, 3);
            MobclickAgent.onEvent(EarnCoinsActivity.this, "watch_video_from_earn");
        } else {
            mIsRewardedVideoLoading = false;
            loadRewardedVideoAd();
            if (Constants.rewardedVideoAd.isLoaded()) {
                Constants.rewardedVideoAd.show();
            } else {
                Toast.makeText(this, R.string.no_video_hint, Toast.LENGTH_SHORT).show();
            }
            MobclickAgent.onEvent(EarnCoinsActivity.this, "fail_watch_video_from_earn");
        }
    }

    //领取I'm Feeling Lucky的奖励
    private void getFeelingLuckyCoins() {
        setFeelingLuckyVisibility(false);

        Constants.START_TIME_FEELING_LUCKY = sp.getLong(Constants.START_TIME_FEELING_LUCKY_PREFIX, -1);
        if (Constants.START_TIME_FEELING_LUCKY == -1) {
            Constants.START_TIME_FEELING_LUCKY = System.currentTimeMillis();

            SharedPreferences.Editor editor = sp.edit();
            editor.putLong(Constants.START_TIME_FEELING_LUCKY_PREFIX, Constants.START_TIME_FEELING_LUCKY);
            editor.commit();
        }

        startActivity(new Intent(EarnCoinsActivity.this, FeelingLuckyActivity.class));
        MobclickAgent.onEvent(EarnCoinsActivity.this, "feeling_lucky");
        startFeelingLuckyClock();
    }

    //领取More Games的金币
    private void getMoreGamesCoins() {
        setMoreGamesVisibility(false);

        Constants.START_TIME_MORE_GAMES = sp.getLong(Constants.START_TIME_MORE_GAMES_PREFIX, -1);
        if (Constants.START_TIME_MORE_GAMES == -1) {
            Constants.START_TIME_MORE_GAMES = System.currentTimeMillis();

            SharedPreferences.Editor editor = sp.edit();
            editor.putLong(Constants.START_TIME_MORE_GAMES_PREFIX, Constants.START_TIME_MORE_GAMES);
            editor.commit();
        }

        //在Google Play中打开ZeekDev的全部APP
        startActivityForResult(new Intent(Intent.ACTION_VIEW,
                Uri.parse("https://play.google.com/store/apps/developer?id=ZeekDev")), Constants.REQUEST_CODE_MORE_GAMES);

        startMoreGamesClock();
    }

    //领取评论App的奖励
    private void getRateAppCoins() {
        //每日只能评论一次
        if (countSign < MAX_SIGN_COUNT) {
            final String appPackageName = getPackageName();
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName));
                startActivityForResult(intent, Constants.REQUEST_CODE_RATE_APP);
            } catch (android.content.ActivityNotFoundException anfe) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName));
                startActivityForResult(intent, Constants.REQUEST_CODE_RATE_APP);
            }
            countSign++;
            SharedPreferences.Editor editor = sp.edit();
            editor.putInt("count_sign", countSign);
            editor.apply();
        } else {
            Toast.makeText(EarnCoinsActivity.this, R.string.has_rated_hint, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        if (resultCode != Activity.RESULT_OK)
//            return;

        //因为在Google Play无法发送返回码，所以只能让用户离开Google Play的时候得到cancel的-1
        switch (requestCode) {
            case Constants.REQUEST_CODE_RATE_APP://启动评分的返回码
                handleCoin(Constants.COINS_EARN_RATE_APP);
                break;
            case Constants.REQUEST_CODE_MORE_GAMES://More Games的返回码
                handleCoin(Constants.COINS_EARN_MORE_GAMES);
                break;
        }
    }

    //处理领取奖励之后的金币问题
    private void handleCoin(int coins) {
        Constants.TOTAL_COIN += coins;
        refreshCoin();

        SoundPoolUtils.play(1);
        Toast.makeText(EarnCoinsActivity.this, getString(R.string.get_coins_hint) + coins, Toast.LENGTH_SHORT).show();

    }

    //设置是否可以领取Bonus奖励
    private void setBonusVisibility(boolean canGetCoins) {
        if (canGetCoins) {
            coinBonus.setVisibility(View.VISIBLE);
            tvBonus.setVisibility(View.GONE);
            btnBonus.setEnabled(true);
        } else {
            coinBonus.setVisibility(View.GONE);
            tvBonus.setVisibility(View.VISIBLE);
            btnBonus.setEnabled(false);
        }
    }

    //设置是否可以领取FeelingLucky奖励
    private void setFeelingLuckyVisibility(boolean canGetCoins) {
        if (canGetCoins) {
            coinFeelingLucky.setVisibility(View.VISIBLE);
            tvFeelingLucky.setVisibility(View.GONE);
            btnFeelingLucky.setEnabled(true);
        } else {
            coinFeelingLucky.setVisibility(View.GONE);
            tvFeelingLucky.setVisibility(View.VISIBLE);
            btnFeelingLucky.setEnabled(false);
        }
    }

    //设置是否可以领取More Games奖励
    private void setMoreGamesVisibility(boolean canGetCoins) {
        if (canGetCoins) {
            coinsMoreGames.setVisibility(View.VISIBLE);
            tvMoreGames.setVisibility(View.GONE);
            btnMoreGames.setEnabled(true);
        } else {
            coinsMoreGames.setVisibility(View.GONE);
            tvMoreGames.setVisibility(View.VISIBLE);
            btnMoreGames.setEnabled(false);
        }
    }

    //启动Bonus倒计时
    private void startBonusClock() {
        long leftTime = Constants.BONUS_COINS_TIME - (System.currentTimeMillis() - Constants.START_TIME_BONUS);//剩余的时间,单位为毫秒

        if (leftTime > 0) {
            //设置一个倒计时
            new CountDownTimer(leftTime, 1000) {

                public void onTick(long millisUntilFinished) {

                    String minute = String.format("%02d", millisUntilFinished / 60000);
                    int second = (int) ((millisUntilFinished % 60000) / 1000);
                    tvBonus.setText(minute + ":" + String.format("%02d", second));
                }

                public void onFinish() {
                    setBonusVisibility(true);

                    SharedPreferences.Editor editor = sp.edit();
                    editor.putLong(Constants.START_TIME_BONUS_PREFIX, -1);
                    editor.commit();
                }
            }.start();
        }

    }

    //启动FeelingLucky倒计时
    private void startFeelingLuckyClock() {
        long leftTime = Constants.FEELING_LUCKY_COINS_TIME - (System.currentTimeMillis() - Constants.START_TIME_FEELING_LUCKY);//剩余的时间,单位为毫秒

        if (leftTime > 0) {
            //设置一个倒计时
            new CountDownTimer(leftTime, 1000) {

                public void onTick(long millisUntilFinished) {

                    String minute = String.format("%02d", millisUntilFinished / 60000);
                    int second = (int) ((millisUntilFinished % 60000) / 1000);
                    tvFeelingLucky.setText(minute + ":" + String.format("%02d", second));
                }

                public void onFinish() {
                    setFeelingLuckyVisibility(true);

                    SharedPreferences.Editor editor = sp.edit();
                    editor.putLong(Constants.START_TIME_FEELING_LUCKY_PREFIX, -1);
                    editor.commit();
                }
            }.start();
        }

    }

    //启动More Games倒计时
    private void startMoreGamesClock() {
        long leftTime = Constants.MORE_GAMES_COINS_TIME - (System.currentTimeMillis() - Constants.START_TIME_MORE_GAMES);//剩余的时间,单位为毫秒

        if (leftTime > 0) {
            //设置一个倒计时
            new CountDownTimer(leftTime, 1000) {

                public void onTick(long millisUntilFinished) {

                    String minute = String.format("%02d", millisUntilFinished / 60000);
                    int second = (int) ((millisUntilFinished % 60000) / 1000);
                    tvMoreGames.setText(minute + ":" + String.format("%02d", second));
                }

                public void onFinish() {
                    setMoreGamesVisibility(true);

                    SharedPreferences.Editor editor = sp.edit();
                    editor.putLong(Constants.START_TIME_MORE_GAMES_PREFIX, -1);
                    editor.commit();
                }
            }.start();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();

        Constants.rewardedVideoAd.setRewardedVideoAdListener(this);
        if (!Constants.rewardedVideoAd.isLoaded()) {
            loadRewardedVideoAd();
        }

        //页面统计
        MobclickAgent.onPageStart("EarnCoins");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();

        MobclickAgent.onPageEnd("EarnCoins"); // 保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息
        MobclickAgent.onPause(this);
    }

    private void refreshCoin() {
        btnCoin.setText(Constants.TOTAL_COIN + "");

        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(Constants.COIN_PREFIX, Constants.TOTAL_COIN);
        editor.commit();

        if (Constants.TOTAL_COIN > 9999) {
            btnCoin.getLayoutParams().width = (int) Tools.convertDpToPx(66, this);
        } else if (Constants.TOTAL_COIN > 999) {
            btnCoin.getLayoutParams().width = (int) Tools.convertDpToPx(58, this);
        }
        countCoin();
    }

    //统计金币总数
    private void countCoin(){
        if(Constants.TOTAL_COIN<10){
            MobclickAgent.onEvent(EarnCoinsActivity.this, "coins_less_10");
        }else if(Constants.TOTAL_COIN<20){
            MobclickAgent.onEvent(EarnCoinsActivity.this, "coins_less_20");
        }else if(Constants.TOTAL_COIN<50){
            MobclickAgent.onEvent(EarnCoinsActivity.this, "coins_less_50");
        }else if(Constants.TOTAL_COIN<100){
            MobclickAgent.onEvent(EarnCoinsActivity.this, "coins_less_100");
        }else if(Constants.TOTAL_COIN<200){
            MobclickAgent.onEvent(EarnCoinsActivity.this, "coins_less_200");
        }else if(Constants.TOTAL_COIN<500){
            MobclickAgent.onEvent(EarnCoinsActivity.this, "coins_less_500");
        }else if(Constants.TOTAL_COIN<1000){
            MobclickAgent.onEvent(EarnCoinsActivity.this, "coins_less_1000");
        }else if(Constants.TOTAL_COIN<2000){
            MobclickAgent.onEvent(EarnCoinsActivity.this, "coins_less_2000");
        }else{
            MobclickAgent.onEvent(EarnCoinsActivity.this, "coins_less_max");
        }
    }

    //加载视频激励广告
    private void loadRewardedVideoAd() {
        synchronized (mLock) {
            if (!mIsRewardedVideoLoading) {
                mIsRewardedVideoLoading = true;
                Bundle extras = new Bundle();
                extras.putBoolean("_noRefresh", true);
                AdRequest adRequest = new AdRequest.Builder()
                        .addNetworkExtrasBundle(AdMobAdapter.class, extras)
                        .build();
                Constants.rewardedVideoAd.loadAd(getString(R.string.rewarded_ad_unit_id), adRequest);
            }
        }
    }

    //视频激励广告的回调
    @Override
    public void onRewardedVideoAdLoaded() {
        synchronized (mLock) {
            mIsRewardedVideoLoading = false;
        }
        llWatchVideo.setVisibility(View.VISIBLE);
    }

    @Override
    public void onRewardedVideoAdOpened() {

    }

    @Override
    public void onRewardedVideoStarted() {

    }

    @Override
    public void onRewardedVideoAdClosed() {
//        if (!Constants.rewardedVideoAd.isLoaded()) {
//            loadRewardedVideoAd();
//        }
//        loadRewardedVideoAd();
        if (!Constants.rewardedVideoAd.isLoaded()) {
            loadRewardedVideoAd();
            llWatchVideo.setVisibility(View.INVISIBLE);
        } else {
            llWatchVideo.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onRewarded(RewardItem rewardItem) {
        handleCoin(Constants.COINS_EARN_WATCH_VIDEO);
    }

    @Override
    public void onRewardedVideoAdLeftApplication() {

    }

    @Override
    public void onRewardedVideoAdFailedToLoad(int i) {
        llWatchVideo.setVisibility(View.INVISIBLE);
        synchronized (mLock) {
            mIsRewardedVideoLoading = false;
        }
        loadRewardedVideoAd();
    }
}
